<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span style="margin-right:10px">选择商品分类:</span>

          <!-- 级联选择器 -->
          <!-- option 指定数据源 -->
          <!-- prop 指定配置对象 -->
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
            class="cascader"
          ></el-cascader
        ></el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="selectKeys.length !== 3"
            @click="addDialog"
            >添加参数</el-button
          >
          <!-- 表格数据 -->
          <el-table stripe :data="manyTableData">
            <el-table-column type="expand">
              <template v-slot="scope">
                <div>
                  <div class="taglist" v-if="scope.row.attr_vals.length > 0">
                    <el-tag
                      :key="index"
                      v-for="(item, index) in scope.row.attr_vals"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(index, scope.row)"
                    >
                      {{ item }}
                    </el-tag>
                  </div>
                  <!-- 输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ 添加</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column prop="name" label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleted(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="selectKeys.length !== 3"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 表格数据 -->
          <el-table stripe :data="onlyTableData">
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <div>
                  <div v-if="scope.row.attr_vals" class="taglist">
                    <el-tag
                      :key="index"
                      v-for="(item, index) in scope.row.attr_vals"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(index, scope.row)"
                    >
                      {{ item }}
                    </el-tag>
                  </div>
                  <!-- 输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!-- 添加按钮 -->
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ 添加</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column prop="name" label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleted(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      @close="dialogClose"
      :title="title"
      :visible.sync="addDialogVisible"
    >
      <el-form :rules="rules" :model="formObj" ref="formRef">
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="addName"
          label-width="80px"
        >
          <el-input v-model="formObj.addName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      //  商品分类数据列表
      cateList: [],
      selectKeys: [],
      //  级联选择器配置对象
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      //    tabs标签页被激活的tab 名称
      activeName: 'many',
      //  动态参数数据
      manyTableData: [],
      //  静态属性数据
      onlyTableData: [],
      // 添加属性对话框的显示与隐藏
      addDialogVisible: false,
      //  添加参数表单绑定数据
      formObj: {
        addName: ''
      },
      // 对话框的标题
      title: '',
      //  编辑行当前数据
      row: {},
      //  控制添加标签输入框的显示与隐藏
      inputVisible: false,
      //  添加标签输入框绑定数据
      inputValue: '',
      rules: {
        addName: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getCateList()
  },
  methods: {
    //  获取商品分类数据列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('商品分类数据获取失败')
      this.cateList = res.data
    },
    //  级联选择器changge事件
    async parentCateChange () {
      this.getParamsData()
    },
    //  Tabs标签页动态处理函数
    handleTabClick () {
      this.getParamsData()
    },
    //  获取参数列表
    async getParamsData () {
      //  如果选中的不是三级分类则终止
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        //  清空表格数据
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //  获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      //  tag 参数切割成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        //  添加属性控制添加按钮与输入框的显示
        item.inputVisible = false
        //  输入框绑定的值
        item.inputValue = ''
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      //  判断获取的是动态参数还是静态属性
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //  添加参数按钮点击
    addDialog () {
      // 打开添加对话框
      this.addDialogVisible = true
      this.title = this.activeName === 'many' ? '添加动态参数' : '添加静态属性'
    },
    //  添加动态参数或者静态属性
    addParams () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.title.slice(0, 2) === '添加') {
          const { data: res } = await this.$http.post(
            `categories/${this.selectKeys[2]}/attributes`,
            {
              attr_name: this.formObj.addName,
              attr_sel: this.activeName
            }
          )

          if (res.meta.status !== 201) return this.$message.error('添加失败!')
          this.$message.success('添加成功~')
          // //  添加成功就追加到数组中实时渲染
          // if (this.activeName === 'many') {
          //   this.manyTableData.push(res.data)
          // } else {
          //   this.onlyTableData.push(res.data)
          // }
          //  重新获取列表
          this.getParamsData()
        } else {
          const { data: res } = await this.$http.put(
            `categories/${this.selectKeys[2]}/attributes/${this.row.attr_id}`,
            {
              attr_name: this.formObj.addName,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status !== 200) return this.$message.error('更新失败!')
          this.row.attr_name = res.data.attr_name
          this.$message.success('更新成功!')
        }
        //  关闭弹出框
        this.addDialogVisible = false
      })
    },
    //  添加属性对话框关闭
    dialogClose () {
      //  表单重置
      this.$refs.formRef.resetFields()
    },
    //  编辑按钮点击事件
    edit (row) {
      //  打开编辑对话框
      this.addDialogVisible = true
      this.title = this.activeName === 'many' ? '修改动态参数' : '修改静态属性'
      //  修改输入框赋值
      this.formObj.addName = row.attr_name
      this.row = row
    },
    //  删除参数点击事件
    deleted (row) {
      this.$confirm('此操作将永久删除参数/属性, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(
          `categories/${this.selectKeys[2]}/attributes/${row.attr_id}`
        )
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功~')
        //  重新获取参数列表
        this.getParamsData()
      })
    },
    //  添加按钮点击
    showInput (row) {
      //  显示输入框
      row.inputVisible = true
      //  自动获得焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    //  添加属性标签回车或者失去焦点事件
    handleInputConfirm (row) {
      //  输入内容为空处理
      if (row.inputValue.trim() === '') {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      //  调用方法发起添加请求
      this.setParams(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    //  设置参数
    async setParams (row) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectKeys[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status === 200) {
        this.$message.success('参数修改成功~')
      } else {
        this.$message.error('参数修改失败!')
      }
    },
    //  标签关闭
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.setParams(row)
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 20px 0;
  span {
    font-size: 16px;
  }
}
.taglist {
  display: inline-block;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
